<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="银行账号" prop="bankCardAccount">
        <el-input
          v-model="queryParams.bankCardAccount"
          placeholder="请输入银行账号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:SettleAccountInfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:SettleAccountInfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:SettleAccountInfo:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="SettleAccountInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="银行账号" align="center" prop="bankCardAccount" />
      <el-table-column label="结算账户类型" align="center" prop="bankCardAccountType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.account_type" :value="scope.row.bankCardAccountType"/>
        </template>
      </el-table-column>
      <el-table-column label="开户名" align="center" prop="bankCardHolder" />
      <el-table-column label="银行卡预留手机号" align="center" prop="bankCardPhone" />
      <el-table-column label="开户行省份" align="center" prop="bankProvince" />
      <el-table-column label="开户行城市" align="center" prop="bankCity" />
      <el-table-column label="开户行网点" align="center" prop="bankSite" />
      <el-table-column label="入账模式" align="center" prop="settleMode">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.settle_model" :value="scope.row.settleMode"/>
        </template>
      </el-table-column>
      <el-table-column label="结算对象" align="center" prop="settleTo" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.settle_to" :value="scope.row.settleTo"/>
        </template>
      </el-table-column>
      <el-table-column label="结算方式" align="center" prop="settleType" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.settle_type" :value="scope.row.settleType"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:SettleAccountInfo:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:SettleAccountInfo:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改结算信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="银行账号" prop="bankCardAccount">
          <el-input v-model="form.bankCardAccount" placeholder="请输入银行账号" />
        </el-form-item>
        <el-form-item label="结算账户类型" prop="bankCardAccountType">
          <el-select v-model="form.bankCardAccountType" placeholder="请选择结算账户类型">
            <el-option
              v-for="dict in dict.type.account_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开户名" prop="bankCardHolder">
          <el-input v-model="form.bankCardHolder" placeholder="请输入开户名" />
        </el-form-item>
        <el-form-item label="银行卡预留手机号" prop="bankCardPhone">
          <el-input v-model="form.bankCardPhone" placeholder="请输入银行卡预留手机号" />
        </el-form-item>
        <el-form-item label="银行卡照片">
          <el-upload
            :file-list="bankCardfileList"
            :on-change="(file,fileList)=>{return uploadChange(file,fileList)}"
            :on-remove="(file,fileList)=>{return handleRemove(file,fileList,'bankCardPic')}"
            action="#"
            ref="bankCardImg"
            list-type="picture-card"
            :on-preview="imgPreview"
            :data="form"
            :http-request="(file)=>{return bankCardHttpRequest(file)}"
            :auto-upload="false">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="imgVisible">
            <img width="100%" :src="imgPath" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="银行编码" prop="bankCode">
          <el-select v-model="form.bankCode" filterable :filter-method="getBank" placeholder="请选择">
            <el-option
              v-for="item in bankOptions"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开户行省份" prop="provinceNo">
          <el-select v-model="form.bankProvince" placeholder="请选择省份">
            <el-option
              v-for="item in provinceOptions"
              :key="item.areaCode"
              :label="item.areaName"
              :value="item.areaCode"
              @click.native="getRegionChildTwo(item)">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开户行城市" prop="cityNo">
          <el-select v-model="form.bankCity" placeholder="请选择城市">
            <el-option
              v-for="item in cityOptions"
              :key="item.areaCode"
              :label="item.areaName"
              :value="item.areaCode"
              @click.native="getBranchList()">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开户行网点" prop="bankSite">
          <el-select v-model="form.unionpayCode" filterable placeholder="请选择">
            <el-option
              v-for="item in branchsOptions"
              :key="item.code"
              :label="item.name"
              :value="item.code"
              @click.native="getLabel(item.name)">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="非法人身份证背面">
          <el-upload
            :file-list="idCardBackfileList"
            action="#"
            :multiple="false"
            ref="idCardBackImg"
            list-type="picture-card"
            :on-preview="imgPreview"
            :data="form"
            :on-remove="(file,fileList)=>{return handleRemove(file,fileList,'nonLegalPersonCertificateBackPic')}"
            :on-change="(file,fileList)=>{return uploadChange(file,fileList)}"
            :http-request="(file)=>{return idCardBankHttpRequest(file)}"
            :auto-upload="false">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="非法人证件有效截止日期" prop="nonLegalPersonEndDate">
          <el-date-picker clearable size="small"
            v-model="form.nonLegalPersonCertificateEndDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择非法人证件有效截止日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="非法人身份证正面">
          <el-upload
            :file-list="idCardFontfileList"
            action="#"
            ref="idCardFontImg"
            list-type="picture-card"
            :on-preview="imgPreview"
            :data="form"
            :http-request="(file)=>{return idCardFontHttpRequest(file)}"
            :on-remove="(file,fileList)=>{return handleRemove(file,fileList,'nonLegalPersonCertificateFrontPic')}"
            :on-change="(file,fileList)=>{return uploadChange(file,fileList)}"
            :auto-upload="false">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="非法人证件号" prop="nonLegalPersonFontNo">
          <el-input v-model="form.nonLegalPersonCertificateNo" placeholder="请输入非法人证件号" />
        </el-form-item>
        <el-form-item label="非法人证件有效开始日期" prop="nonLegalPersonStartDate">
          <el-date-picker clearable size="small"
            v-model="form.nonLegalPersonCertificateStartDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择非法人证件有效开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="非法人证件类型" prop="nonLegalPersonType">
          <el-select v-model="form.nonLegalPersonCertificateType" placeholder="请选择非法人证件类型">
            <el-option
              v-for="dict in dict.type.idCard_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="非法人结算授权函" prop="nonLegalPersonSetAutPic">
          <el-upload
            :file-list="nonLegalPersonSetAutfileList"
            action="#"
            ref="nonLegalPersonSetAutImg"
            list-type="picture-card"
            :on-preview="imgPreview"
            :data="form"
            :http-request="(file)=>{return nonLegalPersonSetAutHttpRequest(file)}"
            :on-remove="(file,fileList)=>{return handleRemove(file,fileList,'nonLegalPersonSettleAuthorizationLetterPic')}"
            :on-change="(file,fileList)=>{return uploadChange(file,fileList)}"
            :auto-upload="false">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="入账模式" prop="settleMode">
          <el-select v-model="form.settleMode" placeholder="请选择入账模式">
            <el-option
              v-for="dict in dict.type.settle_model"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="结算对象" prop="settleTo">
          <el-select v-model="form.settleTo" placeholder="请选择结算对象">
            <el-option
              v-for="dict in dict.type.settle_to"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="结算方式" prop="settleType">
          <el-select v-model="form.settleType" placeholder="请选择结算方式">
            <el-option
              v-for="dict in dict.type.settle_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSettleAccountInfo, getSettleAccountInfo, delSettleAccountInfo, addSettleAccountInfo, updateSettleAccountInfo,getRegionRoot,getBanks,getBranchs } from "@/api/posp/SettleAccountInfo";

export default {
  name: "SettleAccountInfo",
  dicts: ['idCard_type','account_type','settle_model','settle_to','settle_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 结算信息表格数据
      SettleAccountInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bankCardAccount: ''
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      bankCardfileList:[],
      imgVisible:false,
      imgPath:'',
      idCardBackfileList:[],
      idCardFontfileList:[],
      nonLegalPersonSetAutfileList:[],
      formData : new FormData(),
      provinceOptions: {},
      cityOptions:{},
      branchsOptions:{},
      bankOptions:{}
    };
  },
  created() {
    this.getList();
    this.form.merchantId = this.$route.query.merchantId;
    this.getRegionFirst();
    this.getBank('');
  },
  methods: {
    getLabel(value){
      this.form.bankSite = value;
    },
    getBank(bankName){
      let dataObj = {
        page : 1,
        pageSize : 100,
        bankName : bankName
      };
      getBanks(dataObj).then(response => {
        if(response.data && response.data.totalCount > 0){
          this.bankOptions = response.data.list;
        }
      });
    },
    getBranchList(){
      if(this.form.bankProvince && this.form.bankCity && this.form.bankCode){
        let dataObj = {
          page : 1,
          pageSize : 100,
          provinceCode : this.form.bankProvince,
          cityCode : this.form.bankCity,
          bankCode : this.form.bankCode
        };
        getBranchs(dataObj).then(response => {
          this.branchsOptions = response.list
        });
      }
    },
    /** 获取地区 */
    getRegionFirst(){
      let rootObj = {areaLevel: '1'};
      getRegionRoot(rootObj).then(response => {
        this.provinceOptions = response.data;
      });
    },
    getRegionChildTwo(item){
      this.form.bankCity = '';
      this.form.bankSite = '';
      this.form.unionpayCode = '';
      this.cityOptions = [];
      this.branchsOptions = [];
      let rootObj = {areaLevel: '2',parentCode:item.areaCode};
      getRegionRoot(rootObj).then(response => {
        this.cityOptions = response.data;
      });
    },
    beforeUpload(file,fileList){
      let flag = true;
      let isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$modal.msgError("上传图片或视频大小不能超过2MB!")
        flag = false;
      }
      // 验证是否是图片
      if (file.type.indexOf("image/") == -1) {
        this.$modal.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。")
        flag = false;
      }
      if(flag){
        if (fileList.length > 1) {
          fileList.splice(0, 1)
        }
      }else{
        fileList.splice(fileList.length-1, 1);
      }
    },
    imgPreview(file) {
      this.imgPath = file.url;
      this.imgVisible = true;
    },
    bankCardHttpRequest(param){
      this.formData.append('bankCardPicFile', param.file);
    },
    idCardBankHttpRequest(param){
      this.formData.append('nonLegalPersonBackPicFile', param.file);
    },
    idCardFontHttpRequest(param){
      this.formData.append('nonLegalPersonFontPicFile', param.file);
    },
    nonLegalPersonSetAutHttpRequest(param){
      this.formData.append('nonLegalPersonSettleAuthorizationLetterPicFile', param.file);
    },
    handleRemove(file, fileList, funcName) {
      if(fileList.length == 0){
        if(funcName == 'bankCardPic'){
          this.form.bankCardPicLocal = ''
        }else if(funcName == 'nonLegalPersonCertificateBackPic'){
          this.form.nonLegalPersonCertificateBackPicLocal = ''
        }else if(funcName == 'nonLegalPersonCertificateFrontPic'){
          this.form.nonLegalPersonCertificateFrontPicLocal = ''
        }else if(funcName == 'nonLegalPersonSettleAuthorizationLetterPic'){
          this.form.nonLegalPersonSettleAuthorizationLetterPicLocal = ''
        }
      }
    },
    uploadChange(file, fileList) {
      this.beforeUpload(file.raw,fileList);
    },
    /** 查询结算信息列表 */
    getList() {
      this.loading = true;
      listSettleAccountInfo(this.queryParams).then(response => {
        this.SettleAccountInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: '',
        bankCardAccount: '',
        bankCardAccountType: '',
        bankCardHolder: '',
        bankCardPhone: '',
        bankCardPicLocal: '',
        bankCity: '',
        bankCode: '',
        bankProvince: '',
        bankSite: '',
        nonLegalPersonCertificateBackPicLocal: '',
        nonLegalPersonCertificateEndDate: '',
        nonLegalPersonCertificateFrontPicLocal: '',
        nonLegalPersonCertificateNo: '',
        nonLegalPersonCertificateStartDate: '',
        nonLegalPersonCertificateType: '',
        nonLegalPersonSettleAuthorizationLetterPicLocal: '',
        settleMode: '',
        settleTo: '',
        settleType: '',
        unionpayCode: '',
        bankCardPic: '',
        nonLegalPersonCertificateBackPic: '',
        nonLegalPersonCertificateFrontPic: '',
        nonLegalPersonSettleAuthorizationLetterPic: ''
      };
      this.resetForm("form");
      this.formData = new FormData();
      this.bankCardfileList = [];
      this.idCardBackfileList = [];
      this.idCardFontfileList = [];
      this.nonLegalPersonSetAutfileList = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加结算信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      let cityO = {areaLevel: '2',parentCode:row.bankProvince};
      getRegionRoot(cityO).then(response => {
        this.cityOptions = response.data;
      });
      getSettleAccountInfo(id).then(response => {
        this.form = response.data;
        if(this.form.bankCardPicLocal){
          let obj1 = {
            url:process.env.VUE_APP_BASE_API + this.form.bankCardPicLocal,
          };
          this.bankCardfileList.push(obj1);
        }
        if(this.form.nonLegalPersonCertificateBackPicLocal){
          let obj2 = {url:process.env.VUE_APP_BASE_API + this.form.nonLegalPersonCertificateBackPicLocal};
          this.idCardBackfileList.push(obj2);
        }
        if(this.form.nonLegalPersonCertificateFrontPicLocal){
          let obj3 = {url:process.env.VUE_APP_BASE_API + this.form.nonLegalPersonCertificateFrontPicLocal};
          this.idCardFontfileList.push(obj3);
        }
        if(this.form.nonLegalPersonSettleAuthorizationLetterPicLocal){
          let obj4 = {url:process.env.VUE_APP_BASE_API + this.form.nonLegalPersonSettleAuthorizationLetterPicLocal};
          this.nonLegalPersonSetAutfileList.push(obj4);
        }
        this.getBank(this.form.bankSite.slice(0,4));
        this.getBranchList();
        this.open = true;
        this.title = "修改结算信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$refs.bankCardImg.submit();
          this.$refs.idCardBackImg.submit();
          this.$refs.idCardFontImg.submit();
          this.$refs.nonLegalPersonSetAutImg.submit();
          this.formData.append('id',this.form.id);
          this.formData.append('bankCardAccount',this.form.bankCardAccount);
          this.formData.append('bankCardAccountType',this.form.bankCardAccountType);
          this.formData.append('bankCardHolder',this.form.bankCardHolder);
          this.formData.append('bankCardPhone',this.form.bankCardPhone);
          this.formData.append('bankCardPicLocal',this.form.bankCardPicLocal);
          this.formData.append('bankCity',this.form.bankCity);
          this.formData.append('bankCode',this.form.bankCode);
          this.formData.append('bankProvince',this.form.bankProvince);
          this.formData.append('bankSite',this.form.bankSite);
          this.formData.append('bankCardPic',this.form.bankCardPic);
          this.formData.append('nonLegalPersonCertificateBackPic',this.form.nonLegalPersonCertificateBackPic);
          this.formData.append('nonLegalPersonCertificateFrontPic',this.form.nonLegalPersonCertificateFrontPic);
          this.formData.append('nonLegalPersonSettleAuthorizationLetterPic',this.form.nonLegalPersonSettleAuthorizationLetterPic);
          this.formData.append('nonLegalPersonCertificateBackPicLocal',this.form.nonLegalPersonCertificateBackPicLocal);
          this.formData.append('nonLegalPersonCertificateEndDate',this.form.nonLegalPersonCertificateEndDate);
          this.formData.append('nonLegalPersonCertificateFrontPicLocal',this.form.nonLegalPersonCertificateFrontPicLocal);
          this.formData.append('nonLegalPersonCertificateNo',this.form.nonLegalPersonCertificateNo);
          this.formData.append('nonLegalPersonCertificateStartDate',this.form.nonLegalPersonCertificateStartDate);
          this.formData.append('nonLegalPersonCertificateType',this.form.nonLegalPersonCertificateType);
          this.formData.append('nonLegalPersonSettleAuthorizationLetterPicLocal',this.form.nonLegalPersonSettleAuthorizationLetterPicLocal);
          this.formData.append('settleMode',this.form.settleMode);
          this.formData.append('settleTo',this.form.settleTo);
          this.formData.append('settleType',this.form.settleType);
          this.formData.append('unionpayCode',this.form.unionpayCode);
          this.formData.append('merchantId',this.$route.query.merchantId);
          if (this.form.id != '' && this.form.id != null) {
            updateSettleAccountInfo(this.formData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            })
          } else {
            addSettleAccountInfo(this.formData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            })
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除结算信息编号为"' + ids + '"的数据项？').then(function() {
        return delSettleAccountInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>
